package cn.sylinx.hbatis.ext.common.spi;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock;

import cn.sylinx.hbatis.db.common.HbatisService;

public final class HbatisServiceManager {

	private static HbatisService hbatisService;

	private static ReentrantLock lock1 = new ReentrantLock();

	public static HbatisService getHbatisService() {

		if (hbatisService != null) {
			return hbatisService;
		}

		// 加載HbatisService
		loadHbatisService();

		return hbatisService;

	}

	private static void loadHbatisService() {

		try {

			lock1.lock();

			if (hbatisService == null) {

				ServiceLoader<HbatisService> sl = ServiceLoader.load(HbatisService.class);
				Iterator<HbatisService> it = sl.iterator();
				hbatisService = it.hasNext() ? it.next() : null;
			}

		} finally {
			lock1.unlock();
		}

	}

}
